require "socket"

module IRC
  class Connection
    attr_reader :server, :port
    
    def initialize(server, port, options = {})
      @server, @port, @options = server, port, options
      @username = options[:username] || "ruby-irc"
      @nickname = options[:nickname] || "ruby-irc"
      @realname = options[:realname] || "Ruby IRC"
    end
    
    def start
      return false if socket
      connect
      socket.each_line do |line|
        handle(Response.parse(line))
      end
    ensure
      @socket = nil
    end
    
    def send_line(line)
      puts ">>> #{line}"
      socket.puts(line)
    end

    protected
      attr_reader :options, :socket, :username, :nickname, :realname, :response
    
      def connect
        @socket = TCPSocket.open(server, port)
        send_line "USER #{username} 0 0 :#{realname}"
        send_line "NICK #{nickname}"
      end
      
      def handle(response)
        p @response = response
        method = "on_#{response.name.downcase}"
        send(respond_to?(method) ? method : :unknown)
      rescue Exception => e
        puts "error: #{e}"
      end
      
      def unknown; end
      
      def on_ping
        send_line "PONG :#{response.text}"
      end
  end
end
